package com.biz.primus.ms.promotion.dao.redis;

import com.biz.primus.base.exception.utils.AssertUtils;
import com.biz.primus.base.redis.CrudRedisDao;
import com.biz.primus.base.redis.util.RedisUtil;
import com.biz.primus.model.promotion.exception.PromotionExceptionType;
import com.biz.primus.ms.promotion.dao.ro.PurchaseGiftPromotionRo;
import java.util.Objects;
import org.springframework.stereotype.Repository;

/**
 * 买赠促销RedisDao
 *
 * @author david-liu
 */
@Repository
public class PurchaseGiftPromotionRedisDao extends CrudRedisDao<PurchaseGiftPromotionRo, Long> {

    /**
     * 设置买赠促销剩余可参与次数
     *
     * @param promotionId 买赠促销ID
     * @param times 剩余可参与次数
     */
    public void setPurchaseGiftPromotionRemainGainTimesLimitStringKey(Long promotionId, Integer times) {
        AssertUtils.isTrue(Objects.nonNull(times) && Objects.nonNull(promotionId), PromotionExceptionType.ILLEGAL_PARAMETER);
        String remainGainTimesLimitStringKey = this.getPurchaseGiftPromotionRemainGainTimesLimitStringKey(promotionId);
        super.set(remainGainTimesLimitStringKey, RedisUtil.toByteArray(times));
    }

    /**
     * 判断买赠促销是否还可参与
     *
     * @param promotionId 促销ID
     * @return boolean
     */
    public boolean canPurchaseGiftPromotionBeGained(Long promotionId) {
        AssertUtils.notNull(promotionId, PromotionExceptionType.ILLEGAL_PARAMETER);
        String remainGainTimesLimitStringKey = this.getPurchaseGiftPromotionRemainGainTimesLimitStringKey(promotionId);
        byte[] bytes = super.get(remainGainTimesLimitStringKey);
        Integer remainTimes = RedisUtil.byteArrayToInt(bytes);
        return (Objects.isNull(remainTimes) ? 0 : remainTimes) > 0;
    }

    /**
     * 获取买赠促销剩余可参与次数Redis String Key
     *
     * @param promotionId 促销ID
     * @return Redis String Key
     */
    private String getPurchaseGiftPromotionRemainGainTimesLimitStringKey(Long promotionId) {
        return this.getKeyByParams("remain_gain_times", promotionId);
    }

}
